from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from src.infrastructure.config import config
from src.api.routes import router as api_router
import logging
import os
from datetime import datetime
from src.infrastructure.database import engine
from src.models.favorite_path import FavoritePath  # 导入所有模型

# 创建日志目录
log_dir = "logs"
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
    handlers=[
        # 输出到控制台
        logging.StreamHandler(),
        # 输出到文件，按日期分割
        logging.FileHandler(
            filename=f'logs/app_{datetime.now().strftime("%Y%m%d")}.log',
            encoding='utf-8'
        )
    ]
)

logger = logging.getLogger(__name__)

app = FastAPI(
    title="ContentHarvester",
    description="A platform for downloading content from various sources"
)

# CORS设置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

# 注册路由
app.include_router(api_router, prefix="/api")

@app.on_event("startup")
async def startup_event():
    logger.info("Application starting up...")
    logger.info(f"Loaded configuration: {config.config}")
    
    # 创建数据库表
    try:
        FavoritePath.__table__.create(bind=engine, checkfirst=True)
        logger.info("Database tables created successfully")
    except Exception as e:
        logger.error(f"Error creating database tables: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000) 